<?php

namespace app\admin\controller\xilujob;

use app\admin\library\Auth;
use app\admin\model\xilujob\Area;
use app\common\controller\Backend;
use app\common\library\xilujob\resume\ModuleException;
use app\common\library\xilujob\ResumeLibrary;
use app\common\model\User;
use app\common\model\xilujob\ResumeFile;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Hook;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Resume extends Backend
{
    protected $multiFields = 'black,refreshtime,refresh_date,status,top';

    protected $relationSearch = true;

    protected $noNeedRight = 'detail,save_module,del_module';
    /**
     * Resume模型对象
     * @var \app\admin\model\xilujob\Resume
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\xilujob\Resume;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("blackList", $this->model->getBlackList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                ->with(['user'=>function($q){
                    $q->withField(['id','nickname','avatar','mobile']);
                },'personal'])
                //->with(['user','personal','job_intention.fav_category'])
                //->join('XilujobJobCategory c','jobIntention.fav_category_id=c.id','LEFT')
                ->where($where)
                //->where('user.city_id', $this->siteCity->city_id)
                ->order($sort, $order)
                ->paginate($limit)->each(function ($row){
                    if($row->user){
                        // $row->user->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $row->user->mobile);
                    }
                    if($row->personal){
                        // $row->personal->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $row->personal->mobile);
                    }
                    $row->resume_files = ResumeFile::where('resume_id',$row->id)->where('user_id',$row->user_id)->select();

                });

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        //$this->assign('districts', Area::where('pid',$this->siteCity->city_id)->field('id,name')->select());
        $this->assignconfig('work_experience_options', \app\common\model\xilujob\WorkExperience::getAll());
        $this->assignconfig('salary_options', \app\common\model\xilujob\Salary::getMonthOptions());
        $this->assignconfig('education_level', \app\common\model\xilujob\EducationLevel::getAll());
        $this->assignconfig('areas', \app\common\model\xilujob\Area::getAreaTree());
//        $tree = \app\admin\model\xilujob\JobCategory::getCategoryTree();
//        $categories = $tree->getTreeList($tree->getTreeArray(0), 'category_name');
//        foreach($categories as &$v) {
//            $v['name'] = $v['category_name'];
//        }
//        $this->assign('categories', $categories);
//        $this->assign('education_levels', EducationLevel::getAll());
        return $this->view->fetch();
    }
    public function edit($ids=null) {
        $resume = \app\common\model\xilujob\Resume::getResume($ids,true);

        $resume->personal->hide_mobile = 0;//不隐藏手机信息
        $resume->hide_education = 0;//不隐藏教育经历
        $this->assign('resume', $resume);
        $this->assign('work_experience_options', \app\common\model\xilujob\WorkExperience::getAll());
        $this->assign('work_states', \app\common\model\xilujob\WorkState::getAll());
        $this->assign('salary_options', \app\common\model\xilujob\Salary::getMonthOptions());
        $this->assign('districts', Area::getProvinceAndCity());
        $this->assign('education_levels', \app\common\model\xilujob\EducationLevel::getAll());
        $this->assign('skill_levels', \app\common\model\xilujob\SkillLevel::getAll());
        $this->assign('personal_tag_options', \app\common\model\xilujob\ResumePersonalTag::getAll());
        $this->assign('industry_categories', \app\common\model\xilujob\IndustryCategory::getAll());
        $this->assignconfig('areas', \app\common\model\xilujob\Area::getAreaTree());
        return $this->fetch();
    }

    public function detail($ids) {

        $resume = \app\common\model\xilujob\Resume::getResume($ids, true);

        if($resume->user){
            $resume->user->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $resume->user->mobile);
        }
        if($resume->personal){
            $resume->personal->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $resume->personal->mobile);
        }

        $resume->hide_education = 0;
        $resume->personal->hide_mobile = 0;
        $this->assign('resume', $resume);
        return $this->fetch();
    }

    /**
     * 编辑或添加模块内容
     */
    public function save_module() {
        if(!Auth::instance()->check('xilujob/resume/edit', $this->auth->id)){
            Hook::listen('admin_nopermission', $this);
            $this->error(__('You have no permission'), '');
        }
        $id = $this->request->post('id',null);
        if($id) {
            return $this->edit_module();
        }else {
            return $this->add_module();
        }
    }
    protected function add_module() {
        $module = $this->request->post('module','');
        $resume = \app\common\model\xilujob\Resume::getResume($this->request->param('resume_id'));
        Db::startTrans();
        try {
            $resumeLibrary = ResumeLibrary::getResumeLibrary($resume, User::get($resume->user_id));
            $ret = $resumeLibrary->add($module, $this->request->post());
        }catch (ModuleException $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        } catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        Db::commit();
        $this->success('保存成功','',['model'=>$ret]);
    }
    protected function edit_module() {
        $module = $this->request->post('module','');
        $resume = \app\common\model\xilujob\Resume::getResume($this->request->param('resume_id'));
        Db::startTrans();
        try {
            $resumeLibrary = ResumeLibrary::getResumeLibrary($resume, User::get($resume->user_id));
            $ret = $resumeLibrary->edit($module, $this->request->post());
        }catch (ModuleException $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        Db::commit();
        $this->success('保存成功', '',['model'=>$ret]);
    }
    public function del_module() {
//        if(!Auth::instance()->check('resume/edit,resume_optimization/edit', $this->auth->id)){
//            Hook::listen('admin_nopermission', $this);
//            $this->error(__('You have no permission'), '');
//        }
        $module = $this->request->post('module','');
        Db::startTrans();
        try{
            $resume = \app\common\model\xilujob\Resume::getResume($this->request->post('resume_id'));
            $resumeLibrary = ResumeLibrary::getResumeLibrary($resume, User::get($resume->user_id));
            $ret = $resumeLibrary->del($module, $this->request->post('id'));
        }catch (ModuleException $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }catch (Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }
        Db::commit();
        $this->success('删除成功','', ['model'=>$ret]);
    }

    public function multi($ids = "") {
        if(!$this->auth->check('resume/index')) {
            $this->error(__('You have no permission'));
        }
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids) {
            if ($this->request->has('params')) {
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values || $this->auth->isSuperAdmin()) {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds)) {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $count = 0;
                    foreach ($values as $key=>&$value) {
                        if($key==='refreshtime')
                            $value = date('Y-m-d H:i:s');
                        else if($key==='refresh_date')
                            $value = date('Y-m-d');
                    }
                    Db::startTrans();
                    try {
                        $list = $this->model->where($this->model->getPk(), 'in', $ids)->select();
                        foreach ($list as $index => $item) {
                            $count += $item->allowField(true)->isUpdate(true)->save($values);
                        }
                        Db::commit();
                    } catch (PDOException $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    } catch (Exception $e) {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                    if ($count) {
                        $this->success();
                    } else {
                        $this->error(__('No rows were updated'));
                    }
                } else {
                    $this->error(__('You have no permission'));
                }
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }



}
